﻿using System.Linq;
using System.Collections.Generic;
using Transformable_Engine_v2.Engine.GameObjects.Containers;
using Transformable_Engine_v2.Engine.Global;
using Transformable_Engine_v2.Engine.Graphics;
using Transformable_Engine_v2.Engine.Rendering;
using Transformable_Engine_v2.Engine.Transformable_Math.Geometry;

namespace Transformable_Engine_v2.Engine.GameObjects.Primitives
{
    public class PolygonPrimitive : Container
    {
        public enum LineDrawType
        {
            Points = SFML.Graphics.PrimitiveType.Points,
            Lines = SFML.Graphics.PrimitiveType.Lines,
            LinesStrip = SFML.Graphics.PrimitiveType.LinesStrip,
            Triangles = SFML.Graphics.PrimitiveType.Triangles,
            TrianglesStrip = SFML.Graphics.PrimitiveType.TrianglesStrip,
            TrianglesFan = SFML.Graphics.PrimitiveType.TrianglesFan,
            Quads = SFML.Graphics.PrimitiveType.Quads,
        }

        public LineDrawType DrawType { get; set; }


        private SFML.Graphics.Vertex[] _drawableVertices; 
        public List<Vertex> Vertices { get; set; }

        public override TE_Vector2 AbsolutePosition
        {
            protected set
            {
                base.AbsolutePosition = value;

                if(Vertices != null)
                    foreach (var vertex in Vertices) {
                        vertex.SetAbsolutePosition(AbsolutePosition);
                    }

                _drawableVertices = null;
            }
        }

        public PolygonPrimitive AddVertex(params Vertex[] vertices)
        {
            foreach (var vertex in vertices) {
                Vertices.Add(vertex);
            }

            _drawableVertices = null;

            return this;
        }

        public PolygonPrimitive()
        {
            Vertices = new List<Vertex>();
            DrawType = LineDrawType.TrianglesFan;
        }

        void BuildVertices()
        {
            _drawableVertices = new SFML.Graphics.Vertex[Vertices.Count];
            _drawableVertices = Vertices.Select(v => v.ToSFMLVertex()).ToArray(); 
        }

        public override void Draw()
        {
            if(Visible)
            {
                if(_drawableVertices == null)
                BuildVertices();

                if (ShaderHandler.HasShader)
                    RenderTargetHandler.GetCurrentRenderTarget().Draw(_drawableVertices,
                                                                        (SFML.Graphics.PrimitiveType)DrawType, 
                                                                        ShaderHandler.CurrentShader);
                else
                    RenderTargetHandler.GetCurrentRenderTarget().Draw(_drawableVertices,
                                                                        (SFML.Graphics.PrimitiveType)DrawType);
            }
        }
    }
}